package com.adnaan.backend.service.storage;

import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.config.StorageConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service("localStorageService")
public class LocalStorageService implements StorageService {
    private final StorageConfig storageConfig;

    public LocalStorageService(StorageConfig storageConfig) {
        this.storageConfig = storageConfig;
    }

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ServicesException("上传文件为空");
        }
        String path = storageConfig.getLocal().getPath();
        File directory = new File(path);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                throw new ServicesException("目录创建失败");
            }
        }

        String originalFilename = file.getOriginalFilename();
        String fileName = getFileName(originalFilename);
        try {
            file.transferTo(new File(path + fileName));
            return fileName;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new ServicesException("文件上传失败");
        }
    }

    @Override
    public String getUrl(String fileName) {
        return storageConfig.getLocal().getDomain() + '/' + fileName;
    }

    @Override
    public void delete(String fileName) {
        String path = storageConfig.getLocal().getPath();
        File file = new File(path + fileName);
        if (file.exists() && !file.delete()) {
            throw new ServicesException("文件删除失败");
        }
    }

    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }
} 